/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.commons.utils;

import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PBEStringCleanablePasswordEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.core.env.Environment;

import java.util.Objects;

/**
 * <p>
 * 自定义加密工具生成类
 * 支持外部参数加载
 * </p>
 *
 * @author wangyandong
 */
public class CapLazyEncryptor implements StringEncryptor {

    private static Logger log = LoggerFactory.getLogger(CapLazyEncryptor.class);
    private static PBEStringCleanablePasswordEncryptor singleton;

    private static CapPropertyPlaceholderConfigurer configurer;

    public static synchronized PBEStringCleanablePasswordEncryptor getSingleton(final Environment e, final BeanFactory bf) {
        if (Objects.isNull(singleton)) {
            singleton = createDefault(e, bf);
        }
        return singleton;
    }

    private CapLazyEncryptor() {
    }

    private static PBEStringCleanablePasswordEncryptor createDefault(Environment e, BeanFactory bf) {
        configurer = bf.getBean(CapPropertyPlaceholderConfigurer.class);
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        //密钥获取位置代码修改
        config.setPassword(getProperty(e, "jasypt.encryptor.password", "password"));
        config.setAlgorithm(getProperty(e, "jasypt.encryptor.algorithm", "PBEWithMD5AndDES"));
        config.setKeyObtentionIterations(getProperty(e, "jasypt.encryptor.keyObtentionIterations", "1000"));
        config.setPoolSize(getProperty(e, "jasypt.encryptor.poolSize", "1"));
        config.setProviderName(getProperty(e, "jasypt.encryptor.providerName", null));
        config.setProviderClassName(getProperty(e, "jasypt.encryptor.providerClassName", null));
        config.setSaltGeneratorClassName(getProperty(e, "jasypt.encryptor.saltGeneratorClassname", "org.jasypt.salt.RandomSaltGenerator"));
        config.setStringOutputType(getProperty(e, "jasypt.encryptor.stringOutputType", "base64"));
        encryptor.setConfig(config);
        return encryptor;
    }

    private static String getProperty(Environment environment, String key, String defaultValue) {
        if (!propertyExists(environment, key)) {
            log.info("Encryptor config not found for property {}, using default value: {}", key, defaultValue);
        }
        String property = environment.getProperty(key);
        return Objects.isNull(property) ? configurer.getCapProps().getProperty(key, defaultValue) : property;
    }

    private static boolean propertyExists(Environment environment, String key) {
        return environment.getProperty(key) != null || configurer.getCapProps().getProperty(key) != null;
    }

    private static String getRequiredProperty(Environment environment, String key) {
        if (!propertyExists(environment, key)) {
            throw new IllegalStateException(String.format("Required Encryption configuration property missing: %s", key));
        }
        String property = environment.getProperty(key);
        //密钥获取位置代码修改，取不到的话从外部配置读取
        return Objects.isNull(property) ? configurer.getCapProps().getProperty(key) : property;
    }

    /**
     * Encrypt the input message
     *
     * @param message the message to be encrypted
     * @return the result of encryption
     */
    @Override
    public String encrypt(String message) {
        return singleton.encrypt(message);
    }

    /**
     * Decrypt an encrypted message
     *
     * @param encryptedMessage the encrypted message to be decrypted
     * @return the result of decryption
     */
    @Override
    public String decrypt(String encryptedMessage) {
        return singleton.decrypt(encryptedMessage);
    }
}